package com.gin.kotlin.gf2gamecommunity.routes

import androidx.compose.animation.core.tween
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.toRoute
import com.gin.kotlin.enums.DollDuty
import com.gin.kotlin.enums.DollRank
import com.gin.kotlin.form.HeroListForm
import com.gin.kotlin.form.HeroineIdForm
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.composable.DropdownMenuSelector
import com.gin.kotlin.gf2gamecommunity.viewmodel.GameInfoViewModel
import kotlinx.serialization.Serializable


fun NavGraphBuilder.heroineList(onPopBackStack: () -> Unit) = composable<HeroineListRoute>(
    // 从屏幕右侧进入，持续500毫秒
    enterTransition = { slideInHorizontally(tween(500)) { it } },
    // 从屏幕右侧退出，持续500毫秒
    exitTransition = { slideOutHorizontally(tween(500)) { it } },
) {
    HeroineListComposable(route = it.toRoute(), onPopBackStack = onPopBackStack)
}

@Serializable
data class HeroineListRoute(val id: Int = 1)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun HeroineListComposable(route: HeroineListRoute, viewModel: GameInfoViewModel = viewModel(), onPopBackStack: () -> Unit) {
    val maxSelectCount = 10
    var duty by remember { mutableStateOf(DollDuty.ALL) }
    var rank by remember { mutableStateOf(DollRank.ALL) }

    val state = viewModel.heroList.fetch(HeroListForm(duty, rank)).observeAsState()
    val heroineList = state.value?.data
    if (heroineList == null) {
        Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
            CircularProgressIndicator()
        }
        return
    }

    // 请求结果中选中的角色
    val selectedId = heroineList.filter { it.serialId != 999 }.map { it.heroId }
    // 当前选中的ID
    var selected = remember { mutableStateListOf(*selectedId.toTypedArray()) }

    Scaffold(
        topBar = {
            TopAppBar(navigationIcon = {
                IconButton(onClick = { onPopBackStack() }) {
                    Icon(imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "后退")
                }
            }, actions = {}, title = {
                Text("人形展示")
            })
        },

        ) { paddingValues ->
        val modifier = Modifier.padding(paddingValues)
        heroineList.also { list ->
            Column(modifier = modifier.fillMaxSize()) {
                // 过滤器 和 保存按钮
                Row(horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp)) {
                    // 过滤选项
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        DropdownMenuSelector(list = DollDuty.entries, initValue = duty, onSelected = { duty = it }, toText = { it!!.des })
                        DropdownMenuSelector(list = DollRank.entries, initValue = rank, onSelected = { rank = it }, toText = { it!!.des })
                    }
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        Button(onClick = { selected.clear() }) { Text("清空") }
                        Button(onClick = { selected.clear(); selected.addAll(selectedId) }) { Text("重置") }
                        Button(onClick = { viewModel.setHeroSeq(HeroListForm(duty, rank), HeroineIdForm(selected)) }) { Text("保存") }
                    }
                }

                // 人形显示
                LazyVerticalGrid(columns = GridCells.Fixed(4), horizontalArrangement = Arrangement.spacedBy(4.dp),
                    verticalArrangement = Arrangement.spacedBy(4.dp)) {
                    items(items = list) { heroine ->
                        val index = selected.indexOf(heroine.heroId)
                        Box(contentAlignment = Alignment.TopEnd, modifier = Modifier.clickable {
                            // 点击移除或添加到选中列表
                            if (index > -1) {
                                selected.removeAt(index)
                            } else if (selected.size < maxSelectCount) {
                                selected.add(heroine.heroId)
                            } else {
                                App.toast("最多选择 $maxSelectCount 名人形")
                            }
                        }) {
                            HeroineGridCard(heroine)
                            Box(contentAlignment = Alignment.TopEnd, modifier = Modifier
                                .fillMaxSize()
                                .padding(top = 6.dp, end = 8.dp)) {
                                Box(contentAlignment = Alignment.Center, modifier = Modifier
                                    .clip(CircleShape)
                                    .background(if (index > -1) Color.Red else Color.Gray)
                                    .size(20.dp)) {
                                    if (index > -1) Text((index + 1).toString(), color = Color.White)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
